package ntu.edu.sg;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


// GameView is the SurfaceView that contains the "canvas" of the playing field
// This is where the game graphics are being rendered
public class GameView extends SurfaceView implements SurfaceHolder.Callback
{
	
	// a handler to the GameThread class
	private GameThread _thread;
	
	// GameView constructor
	public GameView(Context context, AttributeSet attrs) {
		super(context, attrs);
	
		// To listen for the surface holder events
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		setFocusable(true); 
		
		// Instantiate the thread
		_thread = new GameThread(holder, context, new Handler());
	}  
	
	// Overriding key press events, and calls the 
	// function in the instantiated thread
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent msg) {
		return _thread.getGameState().keyPressed(keyCode, msg);
	}
	
	// Overriding screen touch events, and calls the 
	// method in the instantiated thread	
	@Override 
	public boolean onTouchEvent(MotionEvent event){
		return _thread.getGameState().screenTouch(event);
	}
	
	// Mandatory since we implements the surfaceholder callback
	// but we are not using it. Can ignore
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	}
	
	// Overriding SurfaceCreated method, 
	// which is the entrance point of GameView
	// All it does is calls 2 methods with the 
	// instantiated thread
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		_thread.setRunning(true);
		_thread.start();
	}
	
	// Overriding surfaceDestroyed method, 
	// which is the exit point of GameView
	// All it does is calls a method with the 
	// instantiated thread
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		_thread.setRunning(false);
	}
	
	// a getter method for GameThread, currently not in use
	// leave it here just in case
	public GameThread getThread() {
		return _thread;
	}
}
